package com.fengstyle.tool.common;

import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.HanyuPinyinVCharType;

import java.util.function.Function;

/**
 * 中文转拼音
 * @author yuhf
 */
public class PinyinUtil {

    public static String chineseToPinyin(String chinese){
        return chineseToPinyin(chinese, getDefaultFormat());
    }

    public static String chineseToPinyin(String chinese, HanyuPinyinOutputFormat format){
        return chineseToPinyin(chinese, format, (pinyin) -> String.join(",", pinyin));
    }

    public static String chineseToPinyin(String chinese, Function<String [], String> function){
        return chineseToPinyin(chinese, getDefaultFormat(), function);
    }

    public static String chineseToPinyin(String chinese, HanyuPinyinOutputFormat format, Function<String [], String> function){
        StringBuilder result = new StringBuilder();
        try{
            for (char c : chinese.toCharArray()){
                //如果是汉字
                if(String.valueOf(c).matches("[\\u4e00-\\u9fa5]")){
                    String [] pinyin = PinyinHelper.toHanyuPinyinStringArray(c, format);
                    result.append(function.apply(pinyin)).append(" ");
                }else{
                    result.append(c).append(" ");
                }
            }
        }catch (Exception e){
            System.out.println(e.getMessage());
        }

        return result.toString();
    }

    public static HanyuPinyinOutputFormat getDefaultFormat(){
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        //小写格式
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        //设置拼音声调位置   WITH_TONE_MARK 声调上置；WITHOUT_TONE 不标声调；WITH_TONE_NUMBER 声调右置；
        format.setToneType(HanyuPinyinToneType.WITH_TONE_MARK);
        //设置韵母ü的格式  WITH_U_UNICODE ü 表示；WITH_V  v表示；WITH_U_AND_COLON **u:**表示
        format.setVCharType(HanyuPinyinVCharType.WITH_U_UNICODE);
        return format;
    }

    public static void main(String[] args) {
        System.out.println(chineseToPinyin("行路难。\n" +
                "\n" +
                "金樽清酒斗十千，玉盘珍羞直万钱。\n" +
                "\n" +
                "停杯投箸不能食，拔剑四顾心茫然。\n" +
                "\n" +
                "欲渡黄河冰塞川，将登太行雪满山。\n" +
                "\n" +
                "闲来垂钓碧溪上，忽复乘舟梦日边。\n" +
                "\n" +
                "行路难，行路难，多歧路，今安在？\n" +
                "\n" +
                "长风破浪会有时，直挂云帆济沧海。"));
    }
}
